package com.homework.action;

import com.opensymphony.xwork2.ActionSupport;
import java.io.ByteArrayInputStream;
import java.util.Map;

import javax.servlet.http.Cookie;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.SessionAware;
import com.homework.bean.SecurityCodeBean;
import com.homework.bean.SecurityImageBean;

/**
 * 提供图片验证码
 */
@SuppressWarnings("serial")
public class SecurityCodeImageAction extends ActionSupport implements
		SessionAware {

	// Struts2中Map类型的session
	private Map<String, Object> session;

	// 图片流
	private ByteArrayInputStream imageStream;

	public ByteArrayInputStream getImageStream() {
		return imageStream;
	}

	public void setImageStream(ByteArrayInputStream imageStream) {
		this.imageStream = imageStream;
	}

	public String execute() throws Exception {
		// 如果开启Hard模式，可以不区分大小写
		// String securityCode =
		// SecurityCode.getSecurityCode(4,SecurityCodeLevel.Hard,
		// false).toLowerCase();

		// 获取默认难度和长度的验证码
		String securityCode = SecurityCodeBean.getSecurityCode();
		imageStream = SecurityImageBean.getImageAsInputStream(securityCode);
		// 放入cookie中
		Cookie cookie = new Cookie("securityCode",securityCode);
		cookie.setMaxAge(60);// 1分钟有效时间
		ServletActionContext.getResponse().addCookie(cookie);
		
		return SUCCESS;
	}

	public String getSecurityCode() {
		return null;

	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
